package cn.jolyoulu.common.core.utils.net;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Map;
import java.util.Objects;
import java.util.function.Consumer;

/**
 * @Author: JolyouLu
 * @Date: 2025/2/26 9:59
 * @Version 1.0
 */
@Slf4j
public class HttpUtils {

    private HttpUtils() {
        throw new IllegalStateException("Utility class");
    }

    /**
     * 发送SsePost请求
     *
     * @param httpUrl  请求地址
     * @param headers  请求头参数
     * @param body     请求体参数
     * @param response 响应结果
     */
    public static void sendSsePost(String httpUrl, Map<String, String> headers, String body, Consumer<String> response) {
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "text/event-stream");
        headers.put("Connection", "keep-alive");
        headers.put("Cache-Control", "no-cache");
        send("POST", httpUrl, headers, body, response, response);
    }

    /**
     * 发送JsonPost请求
     *
     * @param httpUrl 请求地址
     * @param headers 请求头参数
     * @param body    请求体参数
     * @return
     */
    public static String sendJsonPost(String httpUrl, Map<String, String> headers, String body) {
        StringBuilder res = new StringBuilder();
        headers.put("Content-Type", "application/json");
        Consumer<String> succeed = res::append;
        Consumer<String> fail = res::append;
        send("POST", httpUrl, headers, body, succeed, fail);
        return res.toString();
    }

    /**
     * 发送JsonGet请求
     *
     * @param httpUrl 请求地址
     * @param headers 请求头参数
     * @param body    请求体参数
     * @return
     */
    public static String sendJsonGet(String httpUrl, Map<String, String> headers, String body) {
        StringBuilder res = new StringBuilder();
        headers.put("Content-Type", "application/json");
        Consumer<String> succeed = res::append;
        Consumer<String> fail = res::append;
        send("GET", httpUrl, headers, body, succeed, fail);
        return res.toString();
    }

    /**
     * 下载图片转化为base64
     *
     * @param imageUrl 请求地址
     * @return
     */
    public static String sendGetPictureBase64(String imageUrl) {
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            sendGetPicture(imageUrl,bos);
            return Base64.getEncoder().encodeToString(bos.toByteArray());
        } catch (IOException e) {
            log.error("error",e);
            return null;
        }
    }

    /**
     * 下载图片
     *
     * @param imageUrl 请求地址
     * @return
     */
    public static void sendGetPicture(String imageUrl,OutputStream outputStream) {
        HttpURLConnection connection = null;
        try {
            URL url = URI.create(imageUrl).toURL();
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(3000); //连接超时
            connection.setReadTimeout(30 * 1000);  //读超时
            connection.setRequestProperty("Connection", "close"); //避免长连接占用资源


            //获取响应code
            int responseCode = connection.getResponseCode();
            log.info("{} {}",imageUrl, responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK
                    || responseCode == HttpURLConnection.HTTP_CREATED
                    || responseCode == HttpURLConnection.HTTP_ACCEPTED) {
                //获取成功信息
                try(InputStream inputStream = connection.getInputStream();) {
                    byte[] buffer = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = inputStream.read(buffer)) != -1) {
                        outputStream.write(buffer, 0, bytesRead); // 批量写入，减少I/O调用
                    }
                    outputStream.flush();
                }
            } else {
                StringBuilder builder = new StringBuilder();
                //获取失败信息
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        builder.append(line);
                    }
                }
                log.error(builder.toString());
            }
        }catch (Exception e){
            log.error("error",e);
        }finally {
            if (connection != null) {
                connection.disconnect(); // 关闭HTTP连接
            }
        }
    }

    /**
     * 发送请求
     *
     * @param reqMethod GET POST HEAD OPTIONS PUT DELETE TRACE
     * @param httpUrl   请求地址
     * @param headers   请求头参数
     * @param body      请求体
     * @param succeed   成功
     * @param fail      失败
     */
    public static void send(String reqMethod,
                            String httpUrl,
                            Map<String, String> headers,
                            String body,
                            Consumer<String> succeed,
                            Consumer<String> fail) {
        HttpURLConnection connection = null;
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(reqMethod);
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                connection.setRequestProperty(entry.getKey(), entry.getValue());
            }
            connection.setDoOutput(true);

            //将body的数据写入到连接中
            try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
                byte[] input = body.getBytes(StandardCharsets.UTF_8);
                wr.write(input, 0, input.length);
            }

            //获取响应code
            int responseCode = connection.getResponseCode();
            log.info("{} {} {} {}", reqMethod, httpUrl, responseCode, connection.getResponseMessage());
            if (responseCode == HttpURLConnection.HTTP_OK
                    || responseCode == HttpURLConnection.HTTP_CREATED
                    || responseCode == HttpURLConnection.HTTP_ACCEPTED) {
                //获取成功信息
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        succeed.accept(line);
                    }
                }
            } else {
                //获取失败信息
                try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        fail.accept(line);
                    }
                }
            }
        } catch (Exception e) {
            log.error("HttpUtils.send error", e);
            fail.accept(e.getMessage());
            if (Objects.nonNull(connection)) {
                connection.disconnect();
            }
        } finally {
            if (Objects.nonNull(connection)) {
                connection.disconnect();
            }
        }
    }
}
